<?php
namespace Home\Controller;
use Think\Controller;

class FundingController extends FrontController {
	public function list($order = 'id desc') {
		//sui
		$this->assign('title', '筹单列表');
		$sui = [
			'funding' => 'active',
			'return' => false,
		];
		$this->assign('sui', $sui);
		//搜索
		$_GET['searchMap']['state'] = '众筹中';
		$_GET['searchMap']['transaction_type'] = ['eq', '发起'];
		$searchMap = $_GET['searchMap'];
		if ($searchMap) {
			foreach ($searchMap as $field => $value) {
				if (!$value) {
					unset($searchMap[$field]);
				}
				if (($field == 'name') && ($value != '')) {
					$searchMap[$field] = ['LIKE', '%' . $value . '%'];
				}
			}
		}
		//获取筹单信息
		$model = D('Funding');
		$count = $model->where($searchMap)->count();
		$page = new \Think\SuiPage($count, C('PAGE_NUM'));
		$show = $page->show();
		$list = $model->order($order)->where($searchMap)->limit($page->firstRow . ',' . $page->listRows)->select();
		//dump($list);die;
		$this->assign('list', $list);
		$this->assign('page', $show);
		$this->display();
	}

	public function detail($id, $consignment_id = '') {
		//筹单信息
		$model = D('Funding')->find($id);
		$this->assign('model', $model);
		$fundingType = D('FundingType')->find($model['funding_type']);
		$this->assign('fundingType', $fundingType);
		$fundingModel = D('Funding' . ucfirst($fundingType['en']));
		$fundingSpecify = $fundingModel->where(['principal_id' => $id])->find();
		$this->assign('fundingSpecify', $fundingSpecify);
		//sui
		$this->assign('title', $model['name'] . '-筹单详情');
		$sui = [
			'funding' => 'active',
			'return' => true,
		];
		//代卖筹单需要跳转回
		$_SESSION['lastFunding']['id'] = $id;
		$_SESSION['lastFunding']['consignment_id'] = $consignment_id;
		$this->assign('sui', $sui);
		$this->display();
	}

	public function buy($id, $consignment_id = '') {
		
		if (!session('用户')) {
			session('afterLogin', U('Funding/detail', ['id' => $id, 'consignment_id' => $consignment_id]));
			$this->redirect('User/login', ['afterLogin' => 1]);
		}

		//众筹信息
		$model = D('Funding')->find($id);
		$this->assign('model', $model);
		$fundingType = D('FundingType')->find($model['funding_type']);
		$this->assign('fundingType', $fundingType);
		$fundingModel = D('Funding' . ucfirst($fundingType['en']));
		$fundingSpecify = $fundingModel->where(['principal_id' => $id])->find();
		$this->assign('fundingSpecify', $fundingSpecify);
		//sui
		$this->assign('title', $model['name'] . '-参与众筹');
		$sui = [
			'customized' => 'active',
			'return' => true,
		];
		$this->assign('sui', $sui);
		//当前登录信息
		$this->assign('user', session('用户'));
		//判断当前用户是否参加过本众筹订单
		$fundingOrder = D('FundingOrder')->where(['user_id' => session('用户')['id'], 'funding_id' => $id])->find();
		
		//if ($fundingOrder['state'] != '已退款') {
		if (($fundingOrder)&&($fundingOrder['state'] != '已退款')) {
			$this->error('您已经参加过该众筹，请前往个人信息页面查看!');
		}
		//判断众筹是否已完成
		$funding_info = M('funding')->where("id = {$_REQUEST['id']}")->find();
		if ($funding_info['already_num'] >= $funding_info['total_num']) {
			D('Funding')->where(['id' => $funding_info['funding_id']])->data(['state' => '众筹成功'])->save();
			//更新和这个筹单相关的所有订单
			D('FundingOrder')->where(['funding_id' => $funding_info['funding_id']])->data(['state' => '待评价'])->save();
			$this->error('抱歉！众筹已经结束');
		}

		
		if (IS_POST) {
			//判断游客数量
			if (count($_POST['tourist']) == 0) {
				$this->error('至少选择一个游客!');
			}
			//计算保险价格
			$insurancePrice = 0;
			foreach ($_POST['insurance'] as $insuranceId) {
				$insurance = D('Insurance')->find($insuranceId);
				$insurancePrice += $insurance['price'] * count($_POST['tourist']);
			}
			//创建筹单订单
			$model = D('FundingOrder');
			unset($data);
			$data['insurance_price'] = $insurancePrice;
			$data['user_id'] = session('用户')['id'];
			$data['funding_id'] = $id;
			$data['tourist_ids'] = implode(',', $_POST['tourist']);
			$data['state'] = '待支付';
			$data['name'] = $_POST['name'];
			$data['phone'] = $_POST['phone'];
			$data['consignment_id'] = $_POST['consignment_id'];
			if (!$model->create($data)) {
				$this->error($model->getError());
				return false;
			}
			$newOrderId = $model->add();
			//保险订单
			foreach ($_POST['tourist'] as $touristId) {
				$tourist = D('Tourist')->find($touristId);
				unset($data);
				$data['user_id'] = session('用户')['id'];
				$data['tourist_id'] = $touristId;
				$data['order_type'] = 'funding_order';
				$data['order_id'] = $newOrderId;
				D('TouristOrder')->data($data)->add();
				foreach ($_POST['insurance'] as $insuranceId) {
					unset($data);
					$data['user_id'] = session('用户')['id'];
					$data['insurance_id'] = $insuranceId;
					$data['order_type'] = 'funding_order';
					$data['order_id'] = $newOrderId;
					$data['name'] = $tourist['name'];
					$data['phone'] = $tourist['phone'];
					$data['id_number'] = $tourist['id_number'];
					D('InsuranceOrder')->data($data)->add();
				}
			}

			$this->success('加入众筹成功!', U('Funding/pay', ['id' => $newOrderId]));
		}
		$this->display();
	}

	// public function contract($id) {
	// 	//sui
	// 	$this->assign('title', '合同内容');
	// 	$sui = [
	// 		'customized' => 'active',
	// 		'return' => true,
	// 	];
	// 	$this->assign('sui', $sui);
	// 	// 订单信息
	// 	$custonizeguider = D('CustomizedGuider')->find($id);
	// 	$this->assign('custonizeguider', $custonizeguider);
	// 	//导游信息
	// 	$guider = D('UserGuider')->join('user on user.id=principal_id')->where(['principal_id' => $custonizeguider['guider_user_id']])->find();
	// 	$this->assign('guider', $guider);
	// 	// 合同信息
	// 	$contract = D('Contract')->where(['type' => '定制导游'])->find();
	// 	$this->assign('contract', $contract['content']);
	// 	$this->display();
	// }

	public function pay($id) {
		//判断当前筹单是否已经成功
		
		$fundingOrder = D('FundingOrder')->find($id);
		
		$touristNum = count(explode(',', $fundingOrder['tourist_ids']));
		$funding = D('Funding')->where(['id' => $fundingOrder['funding_id']])->find();
		$price = $funding['funding_price'] * $touristNum + $fundingOrder['insurance_price'];
		if ($funding['already_num'] == $funding['total_num']) {
			$this->error('当前筹单已经众筹成功,无法继续参与!');
		}
		if (!$this->isWeixin()) {
			$this->redirect('/Api/Alipay/pay', ['out_trade_no' => 'Funding-' . $id, 'subject' => $funding['name'], 'total_fee' => $price]);
		} else {
			$out_trade_no = 'Funding-' . $id;
			$subject = $funding['name'];
			$total_fee = $price;
			session('wxpay_out_trade_no', $out_trade_no);
			session('wxpay_subject', $subject);
			session('wxpay_total_fee', $total_fee);
			$this->redirect('/Api/Wxpay/pay');
		}
	}

	public function sign($id, $type = 'order') {
		if ($type == 'contractOrder') {
			//附加合同签约
			D('ContractOrder')->where(['id' => $id])->data(['buyer_contract_state' => '已签署', 'buyer_contract_time' => time()])->save();
		} elseif ($type == 'order') {
			//修改游客签约状态
			D('Funding')->where(['id' => $id])->data(['user_contract_state' => '已签署'])->save();
			//查看商家签约状态，决定订单状态
			$funding = D('Funding')->find($id);
			if ($funding['seller_contract_state'] == '已签署') {
				//funding状态
				D('Funding')->where(['id' => $id])->data(['state' => '待支付'])->save();
				//定制旅行状态
				D('CustomizedTravel')->where(['funding_id' => $id])->data(['state' => '待支付'])->save();
			}
		}
		$this->success('签约成功!', U('User/CustomizedTravel'));

	}

	public function comment($id, $transaction_type = '发起') {
		//sui
		$this->assign('title', '评价订单');
		$sui = [
			'customized' => 'active',
			'return' => true,
		];
		$this->assign('sui', $sui);
		//订单信息
		if ($transaction_type == '定制') {
			$order_type = 'CustomizedTravel';
			$order_type_alias = 'customized_travel';
		} else {
			$order_type = 'FundingOrder';
			$order_type_alias = 'funding_order';
		}
		$order = D($order_type)->find($id);
		$this->assign('order', $order);
		// 筹单信息
		$funding = D('Funding')->find($order['funding_id']);
		$this->assign('funding', $funding);

		if (IS_POST) {

			$comm_info = M('funding_order')->where("id = $id")->find();
			if($comm_info['state'] == '已完成'){
				$this->success('您已评价成功!', U('User/' . $order_type));
			}
			
			//创建评价
			$model = D('Comment');
			$_POST['user_id'] = session('用户')['id'];
			$_POST['commented_user_id'] = $funding['user_id'];
			$_POST['order_type'] = $order_type;
			$_POST['order_id'] = $id;
			if (!$model->create()) {
				$this->error($model->getError());
				return false;
			}
			$model->add();
			//通知卖家
			notice(session('用户')['id'], $funding['user_id'], '收到新的评价', '收到新的评价，请查看');
			// 完成订单
			D($order_type)->where(['id' => $id])->data(['state' => '已完成'])->save();

			//如果是定制，还需要完成筹单
			if ($transaction_type == '定制') {
				D('Funding')->where(['id' => $funding['id']])->data(['state' => '已完成'])->save();
				//给用户增加积分
				$user = D('User')->find(session('用户')['id']);
				$newCredit = $user['credit'] + $funding['customized_price'];
				D('User')->where(['id' => session('用户')['id']])->data(['credit' => $newCredit])->save();
				//增加积分记录
				unset($data);
				$data['user_id'] = session('用户')['id'];
				$data['amount'] = $funding['customized_price'];
				$data['remark'] = '定制旅游';
				D('CreditRecord')->create($data);
				D('CreditRecord')->add();
			} else {
				//给用户增加积分
				$user = D('User')->find(session('用户')['id']);
				$newCredit = $user['credit'] + $funding['funding_price'];
				D('User')->where(['id' => session('用户')['id']])->data(['credit' => $newCredit])->save();
				//增加积分记录
				unset($data);
				$data['user_id'] = session('用户')['id'];
				$data['amount'] = $funding['funding_price'];
				$data['remark'] = '参与众筹';
				D('CreditRecord')->create($data);
				D('CreditRecord')->add();
			}
			//===金额相关===
			//计算保险价格
			// $insurancePrice = 0;
			// $insuranceOrders = D('InsuranceOrder')->where(['order_type'=>$order_type_alias, 'order_id'=>$id])->select();
			// $touristCount = D('TouristOrder')->where(['order_type'=>$order_type_alias, 'order_id'=>$id])->count();
			// foreach ($insuranceOrders as $insuranceOrder) {
			// 	$insurance = D('Insurance')->find($insuranceOrder['insurance_id']);
			// 	$insurancePrice += $insurance['price'] * $touristCount;
			// }
			unset($data);
			$order = D($order_type)->find($id);
			$touristNum = count(explode(',', $order['tourist_ids']));
			$funding = D('Funding')->find($order['funding_id']);

			if ($_POST['score'] > 3) {
				if ($transaction_type == '定制') {
					//给卖家增加余额
					$user = D('User')->find($funding['user_id']);
					$newBalance = $user['balance'] + $funding['customized_price'];
					D('User')->where(['id' => $user['id']])->data(['balance' => $newBalance])->save();
				} elseif ($transaction_type == '发起') {
					if ($order['consignment_id']) {
						//给代卖用户增加余额
						$user = D('User')->find($order['consignment_id']);
						$newBalance = $user['balance'] + $funding['consignment_price'] * $touristNum;
						D('User')->where(['id' => $order['consignment_id']])->data(['balance' => $newBalance])->save();
						$data1['remark'] = '用户评价订单-' . $funding['name'];

						//给卖家增加余额,需要扣减佣金
						$user = D('User')->find($funding['user_id']);
						$newBalance = $user['balance'] + $funding['funding_price'] * $touristNum - $funding['consignment_price'] * $touristNum;
						D('User')->where(['id' => $user['id']])->data(['balance' => $newBalance])->save();
					} else {
						//给卖家增加余额
						$user = D('User')->find($funding['user_id']);
						$newBalance = $user['balance'] + $funding['funding_price'] * $touristNum;
						D('User')->where(['id' => $user['id']])->data(['balance' => $newBalance])->save();
					}
				}

				$data['remark'] = '用户评价订单-' . $funding['name'];

			} else {
				$data['remark'] = '用户评价订单-' . $funding['name'] . '-差评未支付';
				if ($order['consignment_id']) {
					$data1['remark'] = '用户评价订单-' . $funding['name'] . '-差评未支付';
				}
			}
			//代卖用户逻辑
			if ($order['consignment_id']) {
				//给代卖用户增加金额记录
				unset($data1);
				$data1['user_id'] = $order['consignment_id'];
				$data1['pay_type'] = '-';
				$data1['amount'] = $funding['consignment_price'] * $touristNum;
				$data1['order_type'] = $order_type;
				$data1['order_id'] = $order['id'];
				D('Finance')->create($data1);
				D('Finance')->add();
				//给卖家增加金额记录，需要扣减佣金
				unset($data);
				$data['user_id'] = $funding['user_id'];
				$data['pay_type'] = '-';
				$data['amount'] = $funding['funding_price'] * $touristNum - $funding['consignment_price'] * $touristNum;
				$data['order_type'] = $order_type;
				$data['order_id'] = $order['id'];
				D('Finance')->create($data);
				D('Finance')->add();
			} else {
				//给卖家增加金额记录
				unset($data);
				$data['user_id'] = $funding['user_id'];
				$data['pay_type'] = '-';
				$data['amount'] = $funding['funding_price'] * $touristNum;
				$data['order_type'] = $order_type;
				$data['order_id'] = $order['id'];
				D('Finance')->create($data);
				D('Finance')->add();
			}
			$this->success('评价成功!', U('User/' . $order_type));
		}
		$this->display();
	}

	public function complaint($id, $transaction_type = '发起') {
		//sui
		$this->assign('title', '投诉订单');
		$sui = [
			'customized' => 'active',
			'return' => true,
		];
		$this->assign('sui', $sui);

		//订单信息
		if ($transaction_type == '定制') {
			$order_type = 'CustomizedTravel';
		} else {
			$order_type = 'FundingOrder';
			$order = D('FundingOrder')->find($id);
		}
		$order = D($order_type)->find($id);
		$this->assign('order', $order);
		//检查是否已经发起过投诉
		$complaint = D('Complaint')->where(['order_id' => $id, 'order_type' => $order_type])->find();
		if ($complaint) {
			$this->assign('complaint', $complaint);
		}
		// 筹单信息
		$funding = D('Funding')->find($order['funding_id']);
		$this->assign('funding', $funding);
		if (IS_POST) {
			//创建投诉
			$model = D('Complaint');
			$_POST['user_id'] = session('用户')['id'];
			$_POST['order_type'] = $order_type;
			$_POST['order_id'] = $id;
			if (!$model->create()) {
				$this->error($model->getError());
				return false;
			}
			$model->add();
			notice(session('用户')['id'], 1, '收到新的投诉', '收到新的投诉，请查看');
			// 完成订单
			$this->success('投诉成功,请等待处理!', U('User/' . $order_type));
		}
		$this->display();
	}

	public function CommentList($id) {
		//sui
		$this->assign('title', '发起人评价');
		$sui = [
			'customized' => 'active',
			'return' => true,
		];
		$this->assign('sui', $sui);
		//获取当前发起人的所有评论和订单信息
		$model = D('Comment');
		$count = $model->order('order_id desc')->where(['commented_user_id' => $id])->count();
		$page = new \Think\SuiPage($count, C('PAGE_NUM'));
		$show = $page->show();
		$list = $model->order('order_id desc')->where(['commented_user_id' => $id])->limit($page->firstRow . ',' . $page->listRows)->select();
		//补充订单、筹单、用户信息
		foreach ($list as $key => $value) {
			//用户
			$userInfo = D('User')->find($value['commented_user_id']);
			//订单
			$order = D($value['order_type'])->where(['id' => $value['order_id']])->find();
			//筹单
			$fundingInfo = D('Funding')->where(['id' => $order['funding_id']])->find();
			$list[$key]['user_info'] = $userInfo;
			$list[$key]['order'] = $order;
			$list[$key]['funding_info'] = $fundingInfo;
		}
		$this->assign('list', $list);
		$this->assign('page', $show);
		$this->display();
	}

	public function contract($id, $transaction_type = '发起') {
		//sui
		$this->assign('title', '合同内容');
		$sui = [
			'customized' => 'active',
			'return' => true,
		];

		//区分交易类型
		$this->assign('sui', $sui);
		if ($transaction_type == '定制') {
			$order_type = 'CustomizedTravel';
			$contract_type = '定制旅游';
		} else {
			$order_type = 'FundingOrder';
			$contract_type = '加入众筹';
		}

		// 订单信息
		$order = D($order_type)->find($id);
		$this->assign('order', $order);

		//更新用户合同
		if (IS_POST) {
			if ($_POST['contractOrderId']) {
				// 修改补充合同
				D('ContractOrder')->where(['id' => $_POST['contractOrderId']])->data(['buyer_content' => $_POST['buyer_content'], 'buyer_contract_state' => '未签署', 'seller_contract_state' => '未签署', 'buyer_contract_time' => 0, 'seller_contract_time' => 0])->save();
				$this->success('更新成功!');
			} elseif ($_POST['user_contract']) {
				//修改原有合同
				D('Funding')->where(['id' => $order['funding_id']])->data(['user_contract' => $_POST['user_contract'], 'user_contract_state' => '未签署', 'seller_contract_state' => '未签署'])->save();
				$this->success('更新成功!');
			} else {
				//补充合同
				D('ContractOrder')->add($_POST);
				//增加notice
				$funding = D('Funding')->find($_POST['order_id']);
				notice(1, $funding['user_id'], '系统通知', '有新的补充合同，请尽快查看！');
				$this->success('合同补充成功!');
			}
		}

		// 筹单信息
		$funding = D('Funding')->find($order['funding_id']);
		$this->assign('funding', $funding);
		// 合同信息
		$contract = D('Contract')->where(['type' => $contract_type])->find();
		$this->assign('contract', $contract['content']);

		$this->display();
	}

	public function refund($id, $reason) {
		//增加退款申请
		unset($data);
		$data['order_type'] = 'FundingOrder';
		$data['order_id'] = $id;
		$data['user_id'] = session('用户')['id'];
		$data['reason'] = $reason;
		$data['state'] = '待处理';
		D('Refund')->data($data)->add();
		//修改订单状态
		D('FundingOrder')->where(['id' => $id])->data(['state' => '待退款'])->save();
		$this->success('申请成功!', U('User/FundingOrder'));
	}
    
}
